import React, { useState, useCallback, useRef, useEffect } from 'react';
import { Button, DatePicker, Radio, Icon, Input, Select } from 'antd';
import ProTable from '@ant-design/pro-table';
import { Form } from '@ant-design/compatible';
import { useBoolean, useRequest } from '@umijs/hooks';
import { queryPassengerList, queryCityInfo, queryCompensationData } from './service';
import moment from 'moment';
import AuthComponent from '@/components/Authorized/AuthComponent';

// 自写组件
import CreateForm from './components/CreateForm';
import ListOfClaims from './components/ListOfClaims/index';

// 组件样式
import '@ant-design/compatible/assets/index.css';
import './index.less';
const { Option } = Select;
let _now = new Date(Date.now());
const TableList = (props) => {
  const { location: { state } } = props;
  // 到达航站，出发航站搜索数据
  const { data: selectData } = useRequest(queryCityInfo);
  const [compensationD, setCompensationD] = useState([]);
  // 根据航班号 和 航班日期查询所有赔付单数据
  const { loading: compensationL, run: queryCompensation } = useRequest((params) => queryCompensationData(params), {
    manual: true,
    onSuccess:data =>{
      setCompensationD(data)
    }
  });

    const formatFlightNo = (val) => {
      if (!val) {
        return '';
      } else if (val.length < 3 || /^\D/.test(val)) {
        return ''.toUpperCase.call(val);
      } else if (/^\d{2}/.test(val)) {
        return `3U${val}`;
      } else {
        return val;
      }
    }
  const [_startDate, setStartDate] = useState(_now);
  const [_endDate, setEndDate] = useState(_now);
  const [isCollapse, controlC] = useState(true);
  // 控制弹窗的显示和隐藏
  const { state: stateF, setTrue, setFalse } = useBoolean(false);
 
  const ref = useRef();
  const actionRef = useRef();
  const searchRef = useRef();
  const reloadTable = useCallback(function reloadData() {
    if (searchRef.current) {
      searchRef.current.click();
    }
  }, []);

  const [dataScope, setDataScope] = useState('');
  const onScopeChange = useCallback(e => {
    setDataScope(e.target.value);
  }, []);

  // 防止多次请求
  const [inited, setInited] = useState(false)
  // 第一次加载
  const [firstLoadDate, setFirstLoadDate] = useState(true)
  useEffect(() => {
    if (actionRef.current && inited) {
      reloadTable();
    } else {
      setInited(true)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataScope])

  const beforeSearchSubmit = useCallback(params => {

    params['startDate'] = params.startDate ? params.startDate.format('YYYY-MM-DD') : '';
    params['endDate'] = params.endDate ? params.endDate.format('YYYY-MM-DD') : '';

    if (!isCollapse) {
      return { ...params, status: dataScope }
    } else {
      if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('startDate') === -1) {
          params.startDate = ''
        }
        if (Object.keys(params).indexOf('endDate') === -1) {
          params.endDate = ''
        }
      } else if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          startDate: moment(),
          endDate: moment(),
        });
        setStartDate(_now);
        setEndDate(_now);
      }
      return { ...params, status: dataScope }
    }

  }, [dataScope]);

  // 从消息页跳转过来，初始化加载查询参数
  useEffect(() => {
    if (ref.current && state && sessionStorage.getItem('firstLoad')) {
      ref.current.setFieldsValue({
        startDate: moment(state.flightDate),
        endDate: moment(state.flightDate),
        flightNo: state.flightNo
      })
      reloadTable();
      sessionStorage.removeItem('firstLoad')
    }
  }, [ref.current])

  // 点击表格一行高亮
  const setRowClassName = record => {
    return record.id === rowId ? 'clickRowStyl' : '';
  };

  // 存储每一行的ID
  const [rowId, handleRowId] = useState(null);
  // 存储每一行的航班号和航班日期
  const [flightNumDate, handleFlightNumDate] = useState(null);

  const columns = [
    {
      title: '航班号',
      dataIndex: 'flightNo',
      order: 6,
      renderFormItem: (_, { type, defaultRender, ...rest }) => {
        return <Input 
          {...rest}
          onChange= {e => {
            e.target.value = formatFlightNo(e.target.value);
            rest.onChange(e.target.value)
          }}
          allowClear maxLength={6} placeholder="3U" />;
      }
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      hideInSearch: true,
    },
    {
      title: '航班开始日期',
      hideInTable: true,
      dataIndex: 'startDate',
      order: 5,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{ width: '100%' }}
            allowClear={false}
            format={format}
            {...rest}
            onChange = {e =>{
              setStartDate(e)
              rest.onChange(e)
            }}
            disabledDate={(current)=>{
              // return current && current < moment(_endDate).subtract('180','days');
              return current > _endDate || current < moment(_endDate).subtract('180','days')
            }}
          />
        );
      },
    },
    {
      title: '航班结束日期',
      hideInTable: true,
      dataIndex: 'endDate',
      order: 4,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{ width: '100%' }}
            allowClear={false}
            format={format}
            {...rest}
            onChange = {(e) =>{
              setEndDate(e)
              rest.onChange(e)
            }}
            disabledDate={(current)=>{
              // return  current && current > moment(_startDate).add(180, "days");
              return current < _startDate || current > moment(_startDate).add(180, "days");
            }}
          />
        );
      },
    },
    {
      title: '航段',
      dataIndex: 'segment',
      hideInSearch: true
    },
    {
      title: '箱包补偿单总数',
      dataIndex: 'applyCount',
      hideInSearch: true
    },
    {
      title: '已发放数量',
      dataIndex: 'grantCount',
      hideInSearch: true
    },
    {
      title: '审核中数量',
      dataIndex: 'reviewCount',
      hideInSearch: true
    },
    {
      title: '注销数量',
      dataIndex: 'cancelCount',
      hideInSearch: true
    },
    {
      title: '事故单号',
      dataIndex: 'accidentId',
      hideInTable: true
    },
    {
      // 多个查询选项
      title: '出发航站',
      hideInTable: true,
      dataIndex: 'orgCityAirp',
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {
              selectData && selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      }
    },
    {
      // 多个查询选项
      title: '到达航站',
      hideInTable: true,
      dataIndex: 'dstCityAirp',
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {
              selectData && selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      }
    },
  ];
  return (
    <>
      <ProTable
        options={{density: false, fullScreen: true, reload:false, setting: true }}
        formRef={ref}
        dateFormatter="YYYY-MM-DD"
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
        className='rest-pro-table-form-compact reset'
        size='small'
        formItemProps
        postData={data => {
          return data.map((val, index) => {
            return {
              ...val,
              id: index
            }
          })
        }}
        scroll={{ x: 1000, y:300 }}
        headerTitle={
          <div>
            <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>航班列表</span>
            <Radio.Group onChange={onScopeChange} value={dataScope} buttonStyle="solid">
              <Radio.Button value="">全部</Radio.Button>
              <Radio.Button value="1">我发起的</Radio.Button>
            </Radio.Group>
          </div>
        }
        search={{
          searchText: (
            <span ref={searchRef}>
              查询
            </span>
          ),
          onCollapse: val => {
            controlC(val)
          }
        }}
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={(action, { selectedRows }) => [
          // <AuthComponent authCode="compensation.index.saveData">
          // 	<Button type="primary" onClick={setTrue}>
          //     <Icon type="plus" />
          //     新建补偿
          //   </Button>
          // </AuthComponent>
        ]}
        request={params => {
          if (!params['startDate'] && !params['endDate']) {
            params['startDate'] = moment().format('YYYY-MM-DD');
            params['endDate'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              startDate: moment()
            })
            ref.current.setFieldsValue({
              endDate: moment()
            })
          }
          if (!params['payType']) {
            ref.current.setFieldsValue({
              payType: ''
            })
          }
          setCompensationD([]);
          return queryPassengerList(params);
        }}
        beforeSearchSubmit={beforeSearchSubmit}
        columns={columns}
        rowClassName={setRowClassName}
        onRow={record => {
          return {
            onClick: () => {
                let searchParams = {
                  id: record.id,
                  flightNoS: ref.current.getFieldValue('flightNo'),
                  startDate: ref.current.getFieldValue('startDate'),
                  endDate: ref.current.getFieldValue('endDate'),
                  orgCityAirp: ref.current.getFieldValue('orgCityAirp'),
                  dstCityAirp: ref.current.getFieldValue('dstCityAirp'),
                  payType: ref.current.getFieldValue('payType'),
                  flightNo: record.flightNo,
                  flightDate: record.flightDate,
                  status: dataScope
                };
                sessionStorage.setItem('searchParams', JSON.stringify(searchParams));
                handleRowId(record.id);
                let searchData = {
                  flightNo: record.flightNo,
                  flightDate: record.flightDate,
                  orgCityAirp: record.org,
                  // dstCityAirp: record.dst,
                  status: dataScope,
                  pageSize: 1000,
                  current: 1,
                };
                handleFlightNumDate(searchData);
                queryCompensation(searchData);
            }
          }
        }}
      />
      <ListOfClaims {...{ compensationD, compensationL, flightNumDate, queryCompensation }} />
      <CreateForm
        {...{ stateF, setFalse }}
      />
    </>
  );
};

export default Form.create()(TableList);
